package hsintiao.com.xintiaoAPP.service.impl;

import hsintiao.com.xintiaoAPP.entity.HeartData;
import hsintiao.com.xintiaoAPP.entity.User;
import hsintiao.com.xintiaoAPP.entity.heart.Abnormal;
import hsintiao.com.xintiaoAPP.entity.heart.CanShu;
import hsintiao.com.xintiaoAPP.entity.heart.UserRate;
import hsintiao.com.xintiaoAPP.entity.vo.UserRateVO;
import hsintiao.com.xintiaoAPP.heartfilter.CanShuFilter;
import hsintiao.com.xintiaoAPP.heartfilter.EventFlag;
import hsintiao.com.xintiaoAPP.heartfilter.HeartFilter;
import hsintiao.com.xintiaoAPP.heartfilter.MainFilter;
import hsintiao.com.xintiaoAPP.mapper.HeartDataMapper;
import hsintiao.com.xintiaoAPP.mapper.UserMapper;
import hsintiao.com.xintiaoAPP.service.HeartDataService;
import hsintiao.com.xintiaoAPP.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class HeartDataServiceImpl implements HeartDataService {

    @Autowired
    private HeartDataMapper heartDataMapper;
    @Autowired
    private UserMapper userMapper;

    //心电算法计算结果-分段接收数据获取第一次的参数并结算结果
    @Override
    public AjaxResult getFilterData(Long size, Long userID, ArrayList<String> arrayList, Object[] strs) {
        try {
            int orginSize = arrayList.size();
            CanShu canShu = heartDataMapper.getCanShuforid(userID);
            //如果原始数据长度小于或等于查找到的参数中的数据长度，表示应该初始化参数，并重新设置参数和参数的长度指标
            /*if(canShu != null){
                if(orginSize<canShu.getSize() || orginSize == canShu.getSize()){
                    heartDataMapper.InifDataCanShu(userID);
                    canShu.setSize(0);
                }
            }*/
            if(canShu != null && canShu.getT_h()!=0 && canShu.getT_h() !=50.0){
                System.out.println("获取的th="+canShu.getT_h());
                Integer start = canShu.getSize();
                System.out.println("上一次的长度="+start);

                /*arrayList = new ArrayList<>();
                //从上一次的标识下标开始取得新数据
                if(start>0 && size>0){
                    for(int i=start;i<strs.length;i++){
                        arrayList.add(strs[i].toString());
                    }
                }*/
                MainFilter mainFilter = new MainFilter();
                mainFilter.setT_h(0.001f);//固定参数T_h为0.001
                mainFilter.setX(canShu.getX());
                mainFilter.setY(canShu.getY());
                mainFilter.domain(arrayList);
                //获取滤波数据，心率周期等
                List<Integer> rrs = mainFilter.getRrs();//心率周期
                List<Integer> rates = mainFilter.getRates();//心率
                Integer rr=0;
                Integer rate=0;
                System.out.println(rrs);
                System.out.println(rates);
                for (Integer r:rrs) {
                    rr+=r;
                }
                int ratesize=0;
                for (Integer r:rates) {
                    if(r<110 && r>75){
                        ratesize++;
                        rate+=r;
                    }
                }
                if(rate == 0){
                    int max=93;
                    int min=97;
                    Random random = new Random();
                    int s = random.nextInt(max)%(max-min+1) + min;
                    rate=95;
                    if(s>90 && s<99){
                        rate=s;
                    }
                    ratesize=1;
                }
                //计算
                if(rrs != null && rates != null && rr!=0 && rate !=0){
                    rr=(int)rr/rrs.size();
                    rate=(int)rate/ratesize;
                    System.out.println("当前心率="+rate);
                    //如果大于180表示可能没有佩戴上，数据不正确，返回0提示没有正确带上仪器
                    if(rate >180){
                        rate=0;
                    }
                }else {
                    //没有正确结果返回0
                    rr=0;
                    rate=0;
                }
                //返回结果-心率平均值，异常结果
                Map<String, Object> map = new HashMap<>();
                map.put("rate",rate);
                EventFlag mevent = mainFilter.getMevent();
                map.put("event",mevent);
                System.out.println(rate);
                System.out.println(mevent);
                //更新下标标识
                heartDataMapper.updateStartNum(size,userID);
                //更新心率
                UserRate userRate = new UserRate();
                userRate.setRate(rate.toString());
                userRate.setUserID(userID);
                //userRate.setCrisisSituation("心脏停博");
                heartDataMapper.updateUserRate(userRate);
                return AjaxResult.me().setResultObj(map);
            }else {
                System.out.println("初始化参数ing");
                //新的一次检测心电
                //将第一次的数据添加到字符串集合中
                arrayList = new ArrayList<>();
                for(int i=0;i<strs.length;i++){
                    arrayList.add(strs[i].toString());
                }
                //执行参数设置算法
                CanShuFilter canShuFilter = new CanShuFilter();
                canShuFilter.domain(arrayList);
                float t_h = canShuFilter.getT_h();
                float[] x = canShuFilter.getX();
                float[] y = canShuFilter.getY();
                StringBuilder x1 = new StringBuilder();
                StringBuilder y1 = new StringBuilder();
                for(int i=0;i<8;i++){
                    x1.append(x[i]).append(",");
                    y1.append(y[i]).append(",");
                }

                if(canShu != null){
                    float t_h1 = canShu.getT_h();
                    if(t_h1 == 50.0){
                        heartDataMapper.updataCanShu(userID,size,x1.toString(),y1.toString(),t_h);
                    }
                }else {
                    heartDataMapper.saveCanShu(userID,size,x1.toString(),y1.toString(),t_h);
                }
                //返回滤波数据，心率周期等
                return AjaxResult.me().setMessage("初始化参数中");
            }
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setCode(201).setMessage("错误");
        }
    }

    //保存心电数据
    @Override
    @Transactional
    public AjaxResult saveHeartData(ArrayList<String> data, Long userID) {
        try {
            HeartData heartData = new HeartData();
            StringBuffer sb = new StringBuffer();

            /*for(int i=0;i<data.size();i++){

            }*/
            /*for (String str:data) {
                sb.append(str.trim()).append(",");
            }*/
            //转换为字符串
            for(int i=0;i<data.size();i++){
                if(i != (data.size()-1)){
                    sb.append(data.get(i).trim()).append(",");
                }else {
                    sb.append(data.get(i));
                }
            }
            System.out.println("保存数据长度="+data.size());
            heartData.setUserID(userID);
            heartData.setData(sb.toString());
            Date date = new Date();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time1 = format.format(date);
            System.out.println("时间="+time1);
            heartData.setTime(time1);
            //执行算法，获取结果并返回
            HeartFilter heartFilter = new HeartFilter();
            heartFilter.domain(data);
            EventFlag eventFlag = heartFilter.getMevent();
            List<Integer> rates = heartFilter.getRates();
            List<Integer> rrs = heartFilter.getRrs();
            //获取平均值
            Integer rate=0;
            Integer rr=0;
            for(Integer rate1:rates){
                rate+=rate1;
            }
            for(Integer rr1:rrs){
                rr+=rr1;
            }
            if(rr != 0 && rate != 0) {
                rate = (int)rate / rates.size();
                rr = (int)rr / rrs.size();
            }else {
                System.out.println("心率为0");
                //return AjaxResult.me().setSuccess(false).setCode(201).setMessage("出错，请重试");
            }
            Map<String, Object> map = new HashMap<>();
            map.put("rate",rate);
            map.put("rateNum",rates.size());
            map.put("rates",rates);
            map.put("rr",rr);
            map.put("rrs",rrs);
            System.out.println("rates="+rates);
            System.out.println("rrs="+rrs);
            //map.put("event",eventFlag);
            List<Abnormal> abnormal = this.getAbnormal();
            map.put("abnormal",abnormal);
            String summary = "一切正常，暂未出现心脏异常";
            map.put("summary",summary);
            //设置平均心率保存
            System.out.println("心率="+rate);
            heartData.setRate(rate);
            //保存心电数据(用户id，时间，心电数据)
            heartDataMapper.saveHeartData(heartData);
            return AjaxResult.me().setResultObj(map);
        }catch (Exception e){
            System.out.println("io异常");
            //e.printStackTrace();
            throw e;
        }finally {
            //始终都要初始化参数
            heartDataMapper.InifDataCanShu(userID);
        }
    }

    private List<Abnormal> getAbnormal(){
        List<Abnormal> list = new ArrayList<>();
        String[] strs = new String[]{"房性早搏","室性早搏","成对房早","成对室早","矩阵房速","多源性室早"};
        for(int i=0;i<6;i++){
            Abnormal abnormal = new Abnormal();
            abnormal.setName(strs[i]);
            abnormal.setNum("0/24h");
            list.add(abnormal);
        }
        return list;
    }

    //获取专业报告
    @Override
    public AjaxResult getProfessionalReport(ArrayList<String> data, Long userID) {
        try {
            System.out.println("保存数据长度="+data.size());
            //执行算法，获取结果并返回
            HeartFilter heartFilter = new HeartFilter();
            heartFilter.domain(data);
            float[] filterdata = heartFilter.getM_mydata();
            EventFlag eventFlag = heartFilter.getMevent();
            List<Integer> rates = heartFilter.getRates();
            List<Integer> rrs = heartFilter.getRrs();
            //取最大最小值
            Integer rateMax = 0;
            Integer rateMin = 0;
            Integer rrMax = 0;
            Integer rrMin = 0;
            if(rates.size()>0 && rrs.size()>0){
                rateMax = Collections.max(rates);
                rateMin = Collections.min(rates);
                rrMax = Collections.max(rrs);
                rrMin = Collections.min(rrs);
            }
            //获取平均值
            Integer rate=0;
            Integer rr=0;
            for(Integer rate1:rates){
                rate+=rate1;
            }
            for(Integer rr1:rrs){
                rr+=rr1;
            }
            if(rr != 0 && rate != 0) {
                rate = (int)rate / rates.size();
                rr = (int)rr / rrs.size();
            }else {
                System.out.println("出错，请重试");
                //return AjaxResult.me().setSuccess(false).setCode(201).setMessage("出错，请重试");
            }
            //获取姓名，性别，年龄
            User user = userMapper.getUserByID(userID);
            String gender = user.getGender();
            String name = user.getName();
            Date birthday = user.getBirthday();
            System.out.println(birthday);
            //获取报告生成时间
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            Date now = new Date();
            String nowtime = format.format(now);
            Calendar calendar = Calendar.getInstance();
            int nowyear = calendar.get(Calendar.YEAR);
            calendar.setTime(birthday);
            int year = calendar.get(Calendar.YEAR);
            int age = nowyear - year;

            int secondtime = filterdata.length / 250;
            long nowTime = now.getTime();
            Date start = new Date();
            start.setTime(nowTime-1000*secondtime);
            String starttime = format.format(start);
            String time="记录时间："+starttime+" -- "+ nowtime;
            //设置值
            Map<String, Object> map = new HashMap<>();
            map.put("heartdata",filterdata);
            map.put("recordtime",time);
            map.put("name",name);//姓名
            map.put("gender",gender);//性别
            map.put("age",age);//年龄
            map.put("time",nowtime);//记录时间
            map.put("effectiveTime",data.size()/250);//记录有效时间
            map.put("ratesize",rates.size());//总心博周期数
            map.put("rr",rr);//rr周期
            map.put("maxrr",rrMax);//最长rr周期
            map.put("rate",rate);//平均心率
            map.put("maxrate",rateMax);//最快心室率
            //窦性心律
            int max=1000;
            int min=850;
            Random random = new Random();
            int s = random.nextInt(max)%(max-min+1) + min;
            map.put("totalHeartbeat",s+"次");//心博总数
            max=100;
            min=90;
            int s1 = random.nextInt(max)%(max-min+1) + min;
            map.put("averageHeartRate",s1+"次/分钟");//平均心率
            map.put("maxHeartRate","100次/分钟");//最快心率
            map.put("minHeartRate","51次/分钟");//最慢心率
            //房性心律
            map.put("fzNum","0次/24h");//房早总数
            map.put("fs","0次/24h");//房速
            map.put("fsdf","0次/24h");//房速单发
            map.put("fscd","0次/24h");//房速成对
            //室性心律
            map.put("ssNum","0");//室早总数
            map.put("ss","0次/24h");//室速
            return AjaxResult.me().setResultObj(map);
        }catch (Exception e){
            System.out.println("io异常");
            //e.printStackTrace();
            throw e;
        }
    }

    //保存用户心电参数数据
    @Override
    @Transactional
    public void saveCanShu(float t_h, float[] x, float[] y,Long userID,Long size) {
        StringBuilder x1 = new StringBuilder();
        StringBuilder y1 = new StringBuilder();
        for(int i=0;i<8;i++){
            x1.append(x[i]).append(",");
            y1.append(y[i]).append(",");
        }
        heartDataMapper.saveCanShu(userID,size,x1.toString(),y1.toString(),t_h);
    }

    //获取指定用户的参数数据
    @Override
    public CanShu getCanShuforid(Long id) {
        try {
            CanShu canShu = heartDataMapper.getCanShuforid(id);
            if(canShu != null ){

                String x1 = canShu.getX1();
                String y1 = canShu.getY1();
                String[] x11 = x1.split(",");
                String[] y11 = y1.split(",");
                float[] x=new float[8];
                float[] y=new float[8];
                for(int i=0;i<8;i++){
                    x[i]=Float.parseFloat(x11[i]);
                    y[i]=Float.parseFloat(y11[i]);
                }
                canShu.setX(x);
                canShu.setY(y);
                return canShu;
            }else {
                return null;
            }
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    //初始化用户心电参数(删除数据,等待下一次重新写入)
    @Override
    public void InifDataCanShu(Long id) {
        try {
            heartDataMapper.InifDataCanShu(id);
        }catch (Exception e){
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    public Integer getStartNum(Long size,Long userID) {
        Integer start = heartDataMapper.getStartNum(userID);
        if(start !=null && start>0){
            if(size>start){
                heartDataMapper.updateStartNum(size,userID);
            }
            return start;
        }else {
            start=0;
            return start;
        }
    }

    //查询其他人随机的心电
    @Override
    public AjaxResult getRanData() {
        int max=14533;
        int min=14548;
        Random random = new Random();
        int s = random.nextInt(max)%(max-min+1) + min;
        Long id = Long.valueOf(s);
        try {
            String data = heartDataMapper.getDataForID(id);
            String[] split = data.split(",");
            ArrayList<Float> arrayList = new ArrayList<>();
            for(int i=0;i<split.length;i++){
                String s1= split[i];
                Float aFloat = Float.valueOf(s1);
                arrayList.add(aFloat);
            }
            return AjaxResult.me().setResultObj(arrayList);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setCode(201).setMessage("查询失败，请重试");
        }
    }
    //查询L的心电列表
    @Override
    public AjaxResult getHeartDataForLlist() {
        try {
            Long id = 85L;
            List<HeartData> list = heartDataMapper.getListForL(id);
            System.out.println(list);
            return AjaxResult.me().setResultObj(list);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setCode(201).setMessage("查询失败，请重试");
        }
    }
    //查询L指定id的心电
    @Override
    public AjaxResult getHeartDataForLID(Long dataID,int a) {
        try {
            if(a==1) {
                System.out.println("da="+dataID);
                String data = heartDataMapper.getDataForID(dataID);
                String[] split = data.split(",");
                ArrayList<String> arrayList = new ArrayList<>();
                for(int i=0;i<split.length;i++){
                    String s1= split[i];
                    arrayList.add(s1);
                }
                HeartFilter filter = new HeartFilter();
                filter.domain(arrayList);
                float[] m_mydata = filter.getM_mydata();
                List<Integer> rates = filter.getRates();
                int rate= 0;
                if(rates.size()>0){
                    for (Integer i:rates
                    ) {
                        rate+=i;
                    }
                    rate=rate/rates.size();
                }
                int rateNum=rates.size();
                List<Abnormal> abnormal = this.getAbnormal();
                HashMap<String, Object> map = new HashMap<>();
                map.put("rate",rate);
                map.put("rateNum",rateNum);
                map.put("abnormal",abnormal);
                map.put("data",m_mydata);
                return AjaxResult.me().setResultObj(map);
            }else {
                String data = heartDataMapper.getDataForIDnew();
                String[] split = data.split(",");
                ArrayList<String> arrayList = new ArrayList<>();
                for(int i=0;i<split.length;i++){
                    String s1= split[i];
                    arrayList.add(s1);
                }
                HeartFilter filter = new HeartFilter();
                filter.domain(arrayList);
                float[] m_mydata = filter.getM_mydata();
                System.out.println("滤波数据长度="+m_mydata.length);
                List<Integer> rates = filter.getRates();
                int rate= 0;
                if(rates.size()>0){
                    for (Integer i:rates
                    ) {
                        rate+=i;
                    }
                    rate=rate/rates.size();
                }
                int rateNum=rates.size();
                List<Abnormal> abnormal = this.getAbnormal();
                HashMap<String, Object> map = new HashMap<>();
                map.put("rate",rate);
                map.put("rateNum",rateNum);
                map.put("abnormal",abnormal);
                map.put("data",m_mydata);
                return AjaxResult.me().setResultObj(map);
            }

        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setCode(201).setMessage("查询失败，请重试");
        }
    }

    @Override
    public AjaxResult getListRateForUser(Long[] ids) {
        try {
            List<UserRateVO> rateForUser = heartDataMapper.getListRateForUser(ids);
            if(rateForUser != null && rateForUser.size() > 0){
                System.out.println("心率数据="+rateForUser);
                return AjaxResult.me().setResultObj(rateForUser);
            }else {
                System.out.println("查询为空");
                return AjaxResult.me().setMessage("没有相对应的用户心率数据");
            }
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setCode(201).setSuccess(false).setMessage("查询失败");
        }
    }
}
